/**
 * 频道相关
 */
import request from '@/utils/request'
import store from '@/store'

const DEF_CHANNEL = 'DEF_CHANNEL'
// 获取当前登录用户的所有频道数据/系统默认频道
export function getMyChannels () {
  // return request.get('user/channels')
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    const { user } = store.state
    if (user?.token) {
      resolve(await request.get('user/channels'))
    } else {
      // 获取本地频道数据
      const localChannels = JSON.parse(localStorage.getItem(DEF_CHANNEL)) || null
      if (!localChannels) {
        const res = await request.get('user/channels')
        localStorage.setItem(DEF_CHANNEL, JSON.stringify(res))
        resolve(res)
      } else {
        resolve(localChannels)
      }
    }
  })
}
/**
 * 添加频道
 * @param {*} newChannel 新的频道数据
 */
export function addChannel (newChannel) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    try {
      const { user } = store.state
      if (user?.token) {
        // 调用接口添加
        await request.put('user/channels', {
          channels: newChannel
        })
        resolve()
      } else {
        // 本地更新添加
        // 获取本地频道缓存数据
        const localChannels = JSON.parse(localStorage.getItem(DEF_CHANNEL))
        localChannels.data.channels = newChannel
        localStorage.setItem(DEF_CHANNEL, JSON.stringify(localChannels))
        resolve()
      }
    } catch (error) {
      reject(error)
    }
  })
}

/**
 * 删除频道
 * @param {*} channelId 频道ID
 */
export function delChannel (channelId) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    const { user } = store.state
    // 登录=》调用接口删除
    if (user?.token) {
      await request.delete(`user/channels/${channelId}`)
      resolve()
    } else {
      // 未登录=》删除本地缓存数据
      // 获取本地频道缓存数据
      const localChannels = JSON.parse(localStorage.getItem(DEF_CHANNEL))
      const _data = localChannels.data.channels
      // 根据索引删除频道
      _data.splice(_data.findIndex((item) => item.id === channelId), 1)
      // 更新本地缓存
      localStorage.setItem(DEF_CHANNEL, JSON.stringify(localChannels))
      resolve()
    }
  })
}

// 获取系统中所有的频道
export function getAllChannels () {
  return request.get('channels')
}
